﻿<?php

class CreateController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			//'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('view'),
				'users'=>array('*'),
                
			),
            array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','update','updateAll','delete','yeschapnhan','nochapnhan','suggestTags'),
				'users'=>array('@'),
				//'roles'=>array('admin')

			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$comment = new Comment;
		$model = CreateService::model()->findByPk($id);
		if ($model != null){
			$this->render('view',array('model'=> $model, 'comment'=>$comment));
		}else{
 			$da ="Bạn vào không đúng";
 			$this->render('application.views.site.error',array('data'=>$da));
			}
		//$this->render('view',array('model'=>$this->loadModel($id),));
	}
    
    public function actionIndex()
	{
		$model=new Service;
		if(isset($_POST['Service']))
		{
			$model->attributes=$_POST['Service'];
            if(isset($_POST['Service']['money'])){
                $money = str_replace(".", "",$_POST['Service']['money']);
                $model->money = $money;
            }
            $model->user_id = Yii::app()->user->id;
            $model->time_create = date("Y-m-d H:i:s");
            $model->setScenario('image');
            $model->image = CUploadedFile::getInstance($model,'image');
			if($model->save()){
			  $path = Yii::getPathOfAlias('webroot').'/frontend/data/file/';
                 if ( isset($_POST['Service']["image"]) and $_POST['Service']["image"]){
                    $model->image->saveAs($path.$model->image);
                 }
                 //Yii::app()->getModule('job')->createUserlogs('tbl_service',$model->id,0,1); // 1 la create, 2 update, 3 delete
                 User_Log::setLog('tbl_service',$model->id,0,1);
                 $this->redirect(array('view','id'=>$model->id));
			}
				
		}
        
       	$criteria=new CDbCriteria(array(
		'order'=>'time_update DESC',
		));
		if(isset($_GET['tag']))
			$criteria->addSearchCondition('keyword',$_GET['tag']);

		$dataProvider=new CActiveDataProvider('Service', array(
			'pagination'=>array(
				'pageSize'=>5,
			),
			'criteria'=>$criteria,
		));
        
		$this->render('index',array(
			'model'=>$model,
		));
	}
    
    public function actionUpdate(){
        if (Yii::app()->request->isAjaxRequest)
        {
            //Yii::app()->getModule('job')->createUserlogs('tbl_service',$model->id,0,2);
            $model = new Service();
            $model->id = $_POST['Service']['id'];
    		$model->description = $_POST['Service']['description'];
    		Service::model()->updateByPk($model->id, array('description'=>$model->description));
            echo $model->description;
            User_Log::setLog('tbl_service',$model->id,0,2);
            
        }
    }

	public function loadModel($id)
	{
		$model=Service::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='service-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	public function actionSuggestTags()
	{
		if(isset($_GET['q']) && ($keyword=trim($_GET['q']))!=='')
		{
			$tags=Tag::model()->suggestTags($keyword);
			if($tags!==array())
				echo implode("\n",$tags);
		}
	}
    
    public function actionUpdateAll($id){
        $model=$this->loadModel($id);
        $image_load = $model->image;
        //echo $image_load;
       if($model->user_id == Yii::app()->user->id){
            if(isset($_POST['Service']))
	  	  {
    	  	echo "cho tien";
    			$model->attributes=$_POST['Service'];
                if(isset($_POST['Service']['money'])){
                    $money = str_replace(".", "",$_POST['Service']['money']);
                    $model->money = $money;
                }
                if(CUploadedFile::getInstance($model,'image') == null){
                     $model->image = $image_load;
                }else{
        			$model->setScenario('image');
                    $model->image = CUploadedFile::getInstance($model,'image');
                }
    			if($model->save()){
                    $path = Yii::getPathOfAlias('webroot').'/frontend/data/file/';
                    if ( isset($_POST['Service']['image']) and $_POST['Service']['image'] != null ){
                        $model->image->saveAs($path.$model->image);
                    }
                    
                    User_Log::setLog('tbl_service',$model->id,0,2);
                    $this->redirect(array('view','id'=>$model->id));
    			}
    		}
    		$this->render('index',array(
    			'model'=>$model,
    		));
       }else{
      	     //$this->redirect(array('err','id'=>$model->id));
       }
    }
    
    
    
    
   	public function actionDelete()
	{
        if(isset($_GET['delete'])){
            $id = $_GET['delete'];
            $userCurrent = Yii::app()->user->id;
            $query ="delete from tbl_service where id=".$id." and user_id=".$userCurrent;
            $command=Yii::app()->db->createCommand($query);
            if($command->execute())
            /**
            *Ghi vào log
            */
            User_Log::setLog('tbl_service',$id,0,3);
            Comment::model()->deleteAll($criteria);
            echo "Bạn đã xóa thành công. Chúc bạn thành công với những dịch vụ trong tương lại";
            
        }
       //$this->redirect(array('delete'));
	}
    
    /**
    *Hợp đồng
    */
    public function actionYeschapnhan(){
        if(isset($_GET['bid_id'])){
            $bid_id = $_GET['bid_id'];
            $service_id = $_GET['service_id'];
            $url ="index.php?r=service/bid/hopdong&bidservice_id=".$bid_id."&service_id=".$service_id;
            echo "<script>window.location.href = '".$url."';</script>";
        }
    }
    
    public function actionNochapnhan(){
        if(isset($_GET['nobid_id'])){
            $bid_id = $_GET['nobid_id'];
            /**
            * service_contracted = 2 tức là không đồng ý
            */
            BidService::model()->updateByPk($bid_id,array('service_contracted'=>2));
            echo "Bạn không làm hợp đồng";
        }
    }
    
}
